#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "api/app.h"

#define TIMEMS          qPrintable(QTime::currentTime().toString("HH:mm:ss zzz"))
#define TIME            qPrintable(QTime::currentTime().toString("HH:mm:ss"))
#define QDATE           qPrintable(QDate::currentDate().toString("yyyy-MM-dd"))
#define QTIME           qPrintable(QTime::currentTime().toString("HH-mm-ss"))
#define DATETIME        qPrintable(QDateTime::currentDateTime().toString("yyyy-MM-dd HH:mm:ss"))
#define STRDATETIME     qPrintable(QDateTime::currentDateTime().toString("yyyy-MM-dd-HH-mm-ss"))
#define STRDATETIMEMS   qPrintable(QDateTime::currentDateTime().toString("yyyy-MM-dd-HH-mm-ss-zzz"))

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    this->initForm();
    this->initConfig();
}

MainWindow::~MainWindow()
{
    delete ui;
}

void MainWindow::initForm()
{
    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(on_btnSend_clicked()));

    ui->cboxData->addItems(App::Datas);
}

void MainWindow::initConfig()
{
    ui->txtServerIP->setText(App::TcpServerIP);
    connect(ui->txtServerIP, SIGNAL(textChanged(QString)), this, SLOT(saveConfig()));

    ui->txtServerPort->setText(QString::number(App::TcpServerPort));
    connect(ui->txtServerPort, SIGNAL(textChanged(QString)), this, SLOT(saveConfig()));

    ui->txtServerHostName->setText(App::HostName);
    connect(ui->txtServerHostName, SIGNAL(textChanged(QString)), this, SLOT(saveConfig()));

    this->changeTimer();
}

void MainWindow::saveConfig()
{
    App::TcpServerIP = ui->txtServerIP->text().trimmed();
    App::TcpServerPort = ui->txtServerPort->text().trimmed().toInt();
    App::HostName = ui->txtServerHostName->text().trimmed();
    App::writeConfig();

    this->changeTimer();
}

void MainWindow::changeTimer()
{
    timer->setInterval(App::IntervalTcpClient);
    if (App::AutoSendTcpClient) {
        if (!timer->isActive()) {
            timer->start();
        }
    } else {
        if (timer->isActive()) {
            timer->stop();
        }
    }
}

void MainWindow::append(int type, const QString &data, bool clear)
{
    static int currentCount = 0;
    static int maxCount = 100;

    if (clear) {
        ui->txtMain->clear();
        currentCount = 0;
        return;
    }

    if (currentCount >= maxCount) {
        ui->txtMain->clear();
        currentCount = 0;
    }

    //过滤回车换行符
    QString strData = data;
    strData = strData.replace("\r", "");
    strData = strData.replace("\n", "");

    //不同类型不同颜色显示
    QString strType;
    if (type == 0) {
        strType = "发送";
        ui->txtMain->setTextColor(QColor("darkgreen"));
    } else {
        strType = "接收";
        ui->txtMain->setTextColor(QColor("red"));
    }

    strData = QString("时间[%1] %2: %3").arg(TIMEMS).arg(strType).arg(strData);
    ui->txtMain->append(strData);
    currentCount++;
}

QByteArray MainWindow::sendJson(QString data)
{
    QJsonObject json;
    QJsonDocument docum;
    QByteArray data_json;
    json.insert("atAll", false);
    json.insert("content",data);
    json.insert("messageType","text");
    //json.insert("mobiles","[\"13572061984\"]");

    docum.setObject(json);
    data_json=docum.toJson(QJsonDocument::Compact);
    return data_json;
}

void MainWindow::sendData(const QString &data)
{
    QByteArray buffer;


    QNetworkAccessManager *m_pHttpMgr = new QNetworkAccessManager();
    //设置url
    QString url = "http://" + ui->txtServerIP->text().trimmed() + ":" + ui->txtServerPort->text().trimmed() + "/" + ui->txtServerHostName->text().trimmed();
    //设置头信息
    QNetworkRequest requestInfo;
    requestInfo.setUrl(QUrl(url));
    requestInfo.setHeader(QNetworkRequest::ContentTypeHeader,QVariant("application/json"));

    //发送数据
    QByteArray qByteHttpData = sendJson(data);
    append(0, qByteHttpData);
    QNetworkReply *reply =  m_pHttpMgr->post(requestInfo, qByteHttpData);
    //添加事件循环机制，返回后再运行后面的
    QEventLoop eventLoop;
    connect(reply, SIGNAL(finished()), &eventLoop, SLOT(quit()));
    eventLoop.exec();       //block until finish

    //错误处理
    if (reply->error() == QNetworkReply::NoError)
    {
        qDebug() << "request protobufHttp NoError";
    }
    else
    {
        qDebug()<<"request protobufHttp handle errors here";
        QVariant statusCodeV = reply->attribute(QNetworkRequest::HttpStatusCodeAttribute);
        //statusCodeV是HTTP服务器的相应码，reply->error()是Qt定义的错误码，可以参考QT的文档
        qDebug( "request protobufHttp found error ....code: %d %d\n", statusCodeV.toInt(), (int)reply->error());
    }

    //请求收到的结果
    QByteArray responseByte = reply->readAll();
    append(1, responseByte);
}

void MainWindow::on_btnClear_clicked()
{
    append(0, "", true);
}

void MainWindow::on_btnSend_clicked()
{
    QString data = ui->cboxData->currentText();
    if (data.length() <= 0) {
        return;
    }

    sendData(data);
}





